
"""
The plug-in for RIFF (Resource Interchange File Format) provides the basic
parser framwork to dig into the format.
"""

__version__ = "0.01"

__aof__ = ('Resource Interchange File Format', 'RIF')
__extension__ = (('RIFF Files', ('*.wav', '*.avi')),)


def _buildRiffChunk(idx, entry, source, target, notify, kws):
    _CHUNK = (
        ('ID', 4, 'string,export'),
        ('Size', 4, 'value,export'),
        ('data', '$1', 'eval,object', {'attr': 'extractable'})
    )

    ret, objp, consumed, _, exported = target.parse(
        'Chunk #%d' % idx, _CHUNK, afile=source, **kws)

    if ret:
        kws['offset'] += consumed
        objp.update(content=exported[0])
        entry.append(objp)

    return ret


class _RiffContainer:
    def Execute(self, source, target, notify, **kws):
        _HEADER = (
            ('ID', 4, 'string,verify', {'verified': 'RIFF'}),
            ('Size', 4, 'value,export'),
            ('Type', 4, 'string')
        )

        idx = 1
        entry = target.getEntry()
        target.setEndian('little-endian', kws)

        ret, objectp, consumed, _, _ = target.parse(
            'RIFF', _HEADER, afile=source, **kws)

        if ret:
            entry.append(objectp)
            kws['offset'] += consumed

            while kws['offset'] < len(source):
                ret = _buildRiffChunk(idx, entry, source,
                                      target, notify, kws)
                idx += 1

        return ret


def fmtService():
    return _RiffContainer
